#!/usr/bin/env python

#               Copyright 2010 Morris Blackham
#
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.



import smtplib
import email.utils
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils, Encoders
import mimetypes, sys



def attachment(filename):
	fd = open(filename, 'rb')
	mimetype, mimeencoding = mimetypes.guess_type(filename)
	if mimeencoding or (mimetype is None):
		mimetype ='application/octet-stream'
	maintype, subtype = mimetype.split('/')
	if maintype == 'text':
		retval = MIMEText(fd.read(), _subtype=subtype)
	else:
		retval = MIMEBase(maintype, subtype)
		retval.set_paylod(fd.read())
		Encoders.encode_base64(retval)
	retval.add_header('Content-Disposition', 'attachment', filename = filename)
	fd.close()
	return retval

def send(smtphost, sender, recipient, subject, message, filename):
	#print filename
	if filename == 'blank':
		msg = MIMEText(message)
		body = MIMEText(message, _subtype='plain')


	else:
		msg = MIMEMultipart()
		body = MIMEText(message, _subtype='plain')
		msg.attach(body)
		msg.attach(attachment(filename))
	msg['TO'] = sender
	msg['From'] = recipient
	msg['Subject'] = subject
	msg['Date'] = Utils.formatdate(localtime = 1)
	msg['Message-ID'] = Utils.make_msgid()
	#print msg.as_string()

	server = smtplib.SMTP(smtphost)

	#server.set_debuglevel(True)
	try:
		server.sendmail(sender, [recipient], msg.as_string())
	except:
		print "connection to %s failed" % smtphost
	finally:
		server.quit()
